#coding:utf-8
from selenium import webdriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webscraping import common
import random

import Const

import logging
import logging.config

logging.config.fileConfig(Const.logCfgPath)
logger = logging.getLogger("example01")

try:
    import Image
except ImportError:
    from PIL import Image


def getRowDriver():
     service_args = ['--ignore-ssl-errors=yes', '--load-images=no']
     '''
     proxies = common.read_list(Const.accountDir+'proxies.txt')
     proxy = random.choice(proxies) if proxies else None
     if proxy:
        fragments = common.parse_proxy(proxy)

        if fragments:
            logger.info('host=%s port=%s' % (fragments.host, fragments.port))
            service_args.append('--proxy=%s:%s' % (fragments.host, fragments.port))
            if fragments.username:
                logger.info('name=%s pwd=%s' % (fragments.username, fragments.password))
                service_args.append('--proxy-auth=%s:%s' % (fragments.username, fragments.password))
     '''
     try:
        driver = webdriver.PhantomJS(service_args=service_args)
     except Exception, e:
        logger.error ('get webdriver.PhantomJS failed:%s' % str(e))
        return None
     else:
        driver.set_window_size(1024, 768)
        driver.set_page_load_timeout(const.req_timeout)
        return driver

def clearDriver(driver):
       if driver:
         driver.quit()
       else:
         pass

#from unicode to specify encoding charactors,default is utf-8
def encodingPage(driver,outputEncoding='utf-8'):
    str0 =  driver.page_source

    str  =  str0.encode(outputEncoding)

    return str

def getHtmlSource(driver):
    str = driver.page_source
    return str

def isWebElementExist(driver,xpathValue):
    try:
        driver.find_element_by_xpath(xpathValue)
    except NoSuchElementException,e1:
        return False
    except Exception:
        return False

    return True


def isAllWebElementsExist(driver,xpathValue):
    try:
       elementList =  driver.find_elements_by_xpath(xpathValue)
       if  (not elementList) or  (len(elementList)==0):
            return  False
    except NoSuchElementException,e1:
        return False
    except Exception:
        return False

    return True

def wait(driver,waitSecond,xpathValue,type='visibility'):
    try:
        if type == 'presence':
            WebDriverWait(driver, waitSecond).until(EC.presence_of_element_located((By.XPATH, xpathValue )))
        else:
            WebDriverWait(driver, waitSecond).until(EC.visibility_of_element_located((By.XPATH, xpathValue )))
    except TimeoutException, e:
        return False
    except Exception,ea:
        return False
    return True


def savePic(driver,picName):
   driver.save_screenshot(Const.pngDir+picName)



def setCookies(driver):
    pass

def getCookies():
    pass



if __name__=='__main__':
    driver = getRowDriver()

    driver.get('http://www.baidu.com')
    print driver.current_url
    clearDriver(driver)

